<template>
  <div class="app-container">
    <div class="filter-container">
<!--      <el-input size="small" v-model.trim="listQuery.submit_name" placeholder="姓名" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />-->
      <!-- <el-select size="small" v-model="listQuery.sex" placeholder="性别" clearable style="width: 90px;" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
<!--      <el-input size="small" v-model.trim="listQuery.submit_phone" placeholder="手机" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />-->

<!--      <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 20px">-->
<!--        查询-->
<!--      </el-button>-->
      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button size="small"  :loading="downloadLoading" class="filter-item" type="danger" icon="el-icon-delete" @click="handleAllDelete">
        删除全部数据
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.messages_id }}
        </template>
      </el-table-column>
      <el-table-column label="短信昵称">
        <template slot-scope="scope">
          {{ scope.row.messages_nickname }}
        </template>
      </el-table-column>
      <el-table-column label="短信平台">
        <template slot-scope="scope">
          {{ scope.row.messages_platform }}
        </template>
      </el-table-column>
      <el-table-column label="用户名" >
        <template slot-scope="scope">
          {{ scope.row.messages_name }}
        </template>
      </el-table-column>
      <el-table-column label="发送密码">
        <template slot-scope="scope">
          {{ scope.row.messages_send_pwd }}
        </template>
      </el-table-column>
      <el-table-column label="短信模板">
        <template slot-scope="scope">
          {{ scope.row.messages_template }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="短信模板计费长度【条】" width="95">
        <template slot-scope="scope">
          {{ scope.row.messages_template_length }}
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template slot-scope="scope">
          {{ scope.row.messages_desc }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="dialogFormClose">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" >
        <el-form-item label="短信平台" prop="messages_platform">
          <el-select v-model="temp.messages_platform" placeholder="请选择">
            <el-option
              v-for="item in [{label:'云信通',value:'云信通',disabled:false},{label:'阿里云',value:'阿里云',disabled:true}]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="短信昵称【用于input选择时显示的名字】" prop="messages_nickname" >
          <el-input v-model.trim="temp.messages_nickname" placeholder="请输入短信昵称" />
        </el-form-item>
        <el-form-item label="用户名" prop="messages_name" >
          <el-input v-model.trim="temp.messages_name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="发送密码" prop="messages_send_pwd" >
          <el-input v-model.trim="temp.messages_send_pwd" placeholder="请输入发送密码" />
        </el-form-item>
        <el-form-item label="短信模板" prop="messages_template" >
          <el-input type="textarea" v-model.trim="temp.messages_template" show-word-limit maxlength="999999" placeholder="请输入短信模板" />
        </el-form-item>
        <el-form-item label="短信模板计费长度" prop="messages_template_length" >
          <el-input type="number" v-model.trim="temp.messages_template_length" placeholder="请输入短信模板计费长度" />
        </el-form-item>
        <el-form-item label="备注" prop="" >
          <el-input type="textarea" v-model="temp.messages_desc" placeholder="备注" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
/*.filter-container{*/
/*  padding-bottom: 20px;*/
/*}*/
.filter-item{
  margin: 5px 5px;
  margin-bottom: 20px;
}
</style>
<script>
import { getMessage,addMessage,delMessage,updateMessage,delAllMessage} from '@/api/message'
import Pagination from '@/components/Pagination'
import {createAdmin, updateAdmin} from "@/api/admin"; // secondary package based on el-pagination
export default {
  filters: {
    sexFilter(sex) {
      const sexMap = {
        男: 'success',
        女: 'danger'
      }
      return sexMap[sex]
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      downloadLoading:false,
      table_name:'用户数据导出',
      importanceOptions:['男','女'],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        submit_name: undefined,
        submit_phone: undefined,
        submit_ago: undefined,
        date1:undefined,
        date2:undefined,
      },
      list: null,
      listLoading: true,

      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogStatus:'',
      dialogFormVisible: false,
      rules: {
        messages_nickname:[{ required: true, message: '短信昵称不能为空', trigger: 'blur' }],
        messages_platform:[{ required: true, message: '短信平台不能为空', trigger: 'blur' }],
        messages_name:[{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        messages_send_pwd:[{ required: true, message: '发送密码不能为空', trigger: 'blur' }],
        messages_template:[{ required: true, message: '短信模板不能为空', trigger: 'blur' }],
        messages_template_length:[{ required: true, message: '短信计费长度不能为空', trigger: 'blur' }],
      },
      //新增和编辑数据
      temp: {
        messages_nickname:undefined,
        messages_platform:undefined,
        messages_name:undefined,
        messages_send_pwd:undefined,
        messages_template:undefined,
        messages_template_length:undefined
      },
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    sexVal(e){
      console.log(e)
      return "aaa";
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    fetchData() {
      this.listLoading = true
      getMessage(this.listQuery).then(response => {
        // this.list = response.data.items
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    //新增操作方法
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addMessage(this.temp).then((res) => {
            this.resetTemp()
            if(res.status==200){
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
              this.dialogFormVisible = false
              this.fetchData()
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    resetTemp(){
      this.temp =  {
        messages_nickname:undefined,
        messages_platform:undefined,
        messages_name:undefined,
        messages_send_pwd:undefined,
        messages_template:undefined,
        messages_template_length:undefined
      }
    },
    //关闭弹窗的新增和修改
    dialogFormClose(){
      this.resetTemp()
      this.dialogFormVisible = false
    },
    handleDelete(row, index) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMessage({messages_id:row.messages_id}).then(response => {
          if(response.status==200){
            this.$notify({
              title: 'Success',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          }else{
            this.$notify({
              title: 'Error',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAllDelete(){
      this.$prompt('请输入此账号的密码', '提示', {
        inputType:'password',
        showInput:true,
        inputPlaceholder:'请输入此账号的密码',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:/\S/,
        inputErrorMessage: '密码不为空'
      }).then(({ value }) => {
        delAllMessage({admin_password:value}).then(response=>{
          if(response.status==200){
            this.$notify({
              title: 'Success',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          }else {
            this.$notify({
              title: 'Error',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    //按钮唤起编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑操作方法
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          //console.log(tempData)
          updateMessage(tempData).then((res) => {
            if(res.status==200){
              const index = this.list.findIndex(v => v.messages_id === this.temp.messages_id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: res.msg,
                type: 'success',
                duration: 2000
              })
            }else{
              this.$notify({
                title: 'Error',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },

  },
  components:{
    Pagination
  }
}
</script>
